# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp

import datetime
from dateutil.relativedelta import relativedelta

from .account_move import create2, write2, _set_sub_account

import logging
_logger = logging.getLogger(__name__)

class AccountBalance(models.Model):
    _name = "account.balance"
    _description = "Account Balance"
    _order = "date desc, id desc"
    
    def _get_default_date(self):
        today = fields.Date.context_today(self)
        return datetime.date(today.year, today.month, 1)
            
    state = fields.Selection([('draft', 'Unposted'), ('posted', 'Posted')], 
      string='Status', required=True, readonly=True, copy=False, default='draft',
      help='')

    company_id = fields.Many2one('res.company', string='Company', 
        required=True, index=True, default=lambda self: self.env.user.company_id,
        help="Company related to this")

    date = fields.Date(required=True, index=True, default=_get_default_date)
    line_ids = fields.One2many('account.balance.line', 'balance_id')
    is_init = fields.Boolean(default=False)
    
    def _check_vals(self, vals):
        date = vals.get('date')
        if date:
            if isinstance( date, str):
                date = datetime.datetime.strptime(date,'%Y-%m-%d').date()
            vals['date'] = datetime.date(date.year, date.month,1)
            
        return vals

    @api.multi
    def write(self, vals):
        vals = self._check_vals(vals)
        return super(AccountBalance, self).write(vals)

    @api.model
    def create(self, vals):
        vals = self._check_vals(vals)
        return super(AccountBalance, self).create(vals)

    @api.multi
    def post(self):
        return self.write({'state': 'posted'})

    @api.multi
    def unpost(self):
        if self.ids:
            self.check_access_rights('write')
            self.check_access_rule('write')
            self._cr.execute('UPDATE account_balance '\
                       'SET state=%s '\
                       'WHERE id IN %s', ('draft', tuple(self.ids),))
            self.invalidate_cache()
        return True



class AccountBalanceLine(models.Model):
    
    _name = "account.balance.line"
    _description = "Account Balance Line"
    _order = "date desc, id desc"

    sequence = fields.Integer(help='Used to order line in the balance view', default=10)
    balance_id = fields.Many2one('account.balance', required=True,ondelete="cascade")
    company_id = fields.Many2one('res.company', related='balance_id.company_id', string='Company', store=True, readonly=True)
    date = fields.Date(related='balance_id.date')
    date_maturity = fields.Date(string='Due date')

    account_id = fields.Many2one('account.account', string='Account', required=True, index=True,
        ondelete="cascade", domain=[('deprecated', '=', False)])

    partner_id = fields.Many2one( 'res.partner', string='Partner' )
    product_id = fields.Many2one( 'product.product', string='Product' )
    journal_id = fields.Many2one( 'account.journal', string='Journal' )
    analytic_account_id = fields.Many2one( 'account.analytic.account', string='Analytic Account' )

    # For detail account
    #analytic_tag_id = fields.Many2one('account.analytic.tag', string='Analytic Tags' )

    sub_type = fields.Selection( store=True, related='account_id.sub_type' )
    
    sub_account_id = fields.Many2one('account.sub.account', string='Sub Account', 
                                      ondelete='restrict', index=True )

    sub_account_id_is_auto = fields.Boolean( default=True,
        help="Technical field used to know if the sub_account_id field has been set auto.")

    company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string="Company Currency", readonly=True,
        help='Utility field to express amount currency', store=True)

    type = fields.Selection([
            ('open', 'Open'),
            ('delta', 'Delta'),
        ], required=True, default='delta')

    quantity = fields.Float(digits=dp.get_precision('Product Unit of Measure') )

    debit   = fields.Monetary(currency_field='company_currency_id'  )
    credit  = fields.Monetary(currency_field='company_currency_id')
    balance = fields.Monetary(string='Balance Amount', store=True,compute='_store_balance',currency_field='company_currency_id')

    price = fields.Float(string='Unit Price', digits=dp.get_precision('Product Price'),
        compute='_compute_price' )

    @api.depends('debit', 'credit', 'quantity')
    def _compute_price(self):
        for line in self:
            quantity = line.quantity
            amount = line.debit - line.credit
            line.price  = quantity and amount * 1.00 / quantity or 0.00


    @api.depends('debit', 'credit')
    def _store_balance(self):
        for line in self:
            line.balance = line.debit - line.credit

    @api.model
    def create(self, vals):
        vals = self._check_vals(vals)
        return create2(AccountBalanceLine,self, vals )

    @api.multi
    def write(self, vals):
        vals = self._check_vals(vals)
        return write2(AccountBalanceLine,self, vals )

    def _check_vals(self, vals):
        amount = vals.get('amount', None)
        
        if not amount == None:
            del vals['price']
        
        return vals

    def _set_sub_account(self):
        _set_sub_account(self)
        

